<?php
namespace app\index\controller;

class Common extends \think\Controller
{
    public function _initialize()
    {
        //验证登录
        $this->checkLogin();
        if(session('id')!=NULL){
            $user_id = session('id');
            $data = db('shopping_car')->where("user_id={$user_id}")->order('id desc')->select();
            if($data){
                for($i=0;$i<count($data);$i++){
                    $list[$i] = db('goods_attributes')->alias('a')->join('goods b','a.goods_id=b.id')->join('goods_guigetype c','a.guigeType_id=c.id')->field('a.price,a.jifen,b.*,c.name as guigeName,c.pid')->where("a.id={$data[$i]['attributes_id']}")->order('id desc')->find();
                    $ret = db('goods_guigetype')->where("id={$list[$i]['pid']}")->find();
                    $list[$i]['first_guige_name'] = $ret['name'];
                    $list[$i]['price'] = '¥'.$list[$i]['price'];
                    $list[$i]['car_id'] = $data[$i]['id'];

                    $row=[];
                    foreach( $list as $val )
                    {
                        $img = json_decode($val['src'],true);    //转换格式,json字符串->php数组
                        if($img!=NULL){
                            $val['src']=array($img[0]);
                        }else{
                            $val['src']=array($val['src']);
                        }
                        $thumb_img = json_decode($val['thumb_src'],true);    //转换格式,json字符串->php数组
                        if($thumb_img!=NULL){
                            $val['thumb_src']=array($img[0]);
                        }else{
                            $val['thumb_src']=array($val['thumb_src']);
                        }
                        $row[] = $val;  //存入新数组$row中
                    }
                }
                // dump($row);die;
                $this->assign('carlist',$row);
            }   
        }
    }

    public function checkLogin()
    {
        //验证是否已经登录
        if(session('id')==NULL){
            //未登录
            $this->error('未登录！','login/index');
        }
        if(session('login_time')+10000<time()){
            //过期
            session('id',NULL);
            session('name',NULL);
            session('head_img',NULL);
            $this->error('未登录！','login/index');
        }
        session('login_time',time());
    }
}